<template>
	<view class="container">
		<!-- 顶部状态栏 -->
		<view class="head">
			<view class="back" @tap="goback">
				<uni-icons type="left" color="#fff" size="22"></uni-icons>
			</view>
			<view class="status-bar">
				<view class="status-title">{{ getTitleOrDescByCode(order.status, 'title') }}</view>
				<view class="status-desc">{{ getTitleOrDescByCode(order.status, 'desc') }}</view>
			</view>
		</view>
		
		<!-- 地图容器 -->
		<map 
			id="map"
			class="map-container" 
			:latitude="center.latitude" 
			:longitude="center.longitude" 
			:scale="10"
			:markers="markers" 
			:include-points="markers"
			:polyline="polyline" 
			show-location
		>
		</map>
		
		<!-- 订单信息卡片 -->
		<view class="order-card">
			<view class="up">
				<view class="tags">
					<view class="left">
						<view>
							总里程:{{distance}}km
						</view>
						<view class="price">
							<text>
								{{
									[
										orderTypeEnum.FINISH.code, 
										orderTypeEnum.REFUND_PENDING.code, 
										orderTypeEnum.REFUND_REFUSED.code
									]
									.includes(order.status) ? '花费:' : '预计:' 
								}}
							</text>
							<text class="num">{{ formatAmount(order.price) }}</text>
							<text>(元)</text>
						</view>
					</view>
					<view class="right" v-if="order.driverId" @tap="showDriverInfo">
						<uni-icons type="person" color="19afff"></uni-icons>
						<text>司机信息</text>
					</view>
				</view>
				<view class="from-and-to">
					<view class="from">
						<view class="dot green"></view>
						<view class="text">起点：{{ order.currentAddr }}</view>
					</view>
					<view class="to">
						<view class="dot red"></view>
						<view class="text">终点：{{ order.targetAddr }}</view>
					</view>
				</view>
				<view class="time">
					<view>
						订单号：{{ order.id }}
					</view>
					<view>
						下单时间：{{ order.orderTime }}
					</view>
					<view v-if="[orderTypeEnum.WAIT.code, orderTypeEnum.GET.code, orderTypeEnum.WAITING.code,
								orderTypeEnum.START.code, orderTypeEnum.PENDING_PAY.code].includes(order.status)"
					>
						出发时间：{{ order.hopeTime }}
					</view>
					<view v-if="[orderTypeEnum.PENDING_PAY.code, orderTypeEnum.FINISH.code].includes(order.status)">
						到达时间：{{ order.reachTime }}
					</view>
				</view>
			</view>
			<view class="down">
				<view class="btn btn-cancel" @click="cancelOrder" v-if="[orderTypeEnum.WAIT.code, orderTypeEnum.GET.code, orderTypeEnum.WAITING.code].includes(order.status)">
					取消订单
				</view>
				<view class="btn btn-cancel" @click="applyRefund" v-if="orderTypeEnum.FINISH.code == order.status">
					申请退款
				</view>
				<view class="btn btn-contact" @click="contactDriver" v-if="order.driverPhone">
					联系司机
				</view>
			</view>
		</view>
		
		<!--司机信息弹窗-->
		<uni-popup ref="driverInfoPopupRef">
			<view class="driver-info">
				<view class="avatar">
					<image :src="getDriverAvatarOrDefault(order.profileImg)" mode="aspectFill"></image>
				</view>
				<!--名称和驾龄等-->
				<view class="info">
					<view class="name-and-id">
						<text>{{ order.surname }}师傅</text>
						&nbsp;
						<text>工号:{{ order.driverId }}</text>
					</view>
					<view class="years-and-times">
						<text>驾龄:{{ order.driverAge }}年</text>
						<!-- &nbsp;
						<text>代驾次数:10次</text> -->
					</view>
				</view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { MAP } from '@/utils/qq-map-wx.js'
import { getOrderById, updateStatus } from '@/api/order.js'
import { onLoad } from '@dcloudio/uni-app'
import { polylineArray2LatlonArray } from '@/utils/polylineUtil.js'
import { orderTypeEnum, getTitleOrDescByCode } from '@/utils/orderType.js'
import { formatAmount } from '@/utils/amountUtil.js'
import { getDriverAvatarOrDefault } from '@/utils/imageUtil.js'

// 地图中心点
const center = ref({
	latitude: 39.906036,
	longitude: 116.397697
})

// 标记点
const markers = ref([])
// 路线
const polyline = ref([{
	points: [],
	color: '#3777FF',
	width: 6,
	borderWidth: 5,
	borderColor: '#FFFFFF',
	arrowLine: true // 带箭头的线
}])

// 订单信息
const order = ref({
	id: "",
	businessType: null,
	currentLo: 116.397697,
	currentLa: 39.906036,
	currentAddr: "",
	targetLo: 116.397697,
	targetLa: 39.906036,
	targetAddr: "",
	orderTime: "",
	hopeTime: "",
	receiveTime: null,
	reachTime: null,
	startTime: null,
	endTime: null,
	price: 0,
	userId: "",
	username: "",
	userPhone: "",
	status: -1,
	remark: null,
	driverId: null,
	driverAge: null,
	profileImg: "",
	surname: null,
	name: null,
	driverPhone: null,
	driverStatus: null
})

// 路程距离
const distance = ref(0)

// 司机信息弹窗
const driverInfoPopupRef = ref(null)

// 返回
function goback () {
	uni.navigateBack()
}

// 取消订单
function cancelOrder () {
	uni.showModal({
		title: '取消订单',
		content: '确定要取消订单吗？',
		success: (res) => {
			if (res.confirm) {
				updateStatus({ id: order.value.id, status: orderTypeEnum.CANCEL.code }).then(() => {
					uni.showToast({
						title: '取消成功',
						icon: 'none'
					})
					order.value.status = orderTypeEnum.CANCEL.code
					uni.$emit('user-update-order-status', { id: order.value.id, status: orderTypeEnum.CANCEL.code })
				})
			}
		}
	})
}

// 申请退款
function applyRefund () {
	uni.showModal({
		title: '申请退款',
		content: '申请退款后客服将会通过电话方式联系您，询问具体退款原因。确认申请退款吗？',
		success: (res) => {
			if (res.confirm) {
				updateStatus({ id: order.value.id, status: orderTypeEnum.REFUND_PENDING.code }).then(() => {
					uni.showToast({
						title: '申请成功',
						icon: 'none'
					})
					order.value.status = orderTypeEnum.REFUND_PENDING.code
					uni.$emit('user-update-order-status', { id: order.value.id, status: orderTypeEnum.REFUND_PENDING.code })
				})
			}
		}
	})
}

// 联系司机
function contactDriver () {
	uni.makePhoneCall({
		phoneNumber: order.value.driverPhone,
		success: () => {},
		fail: () => {}
	})
}

// 设置经度纬度高度
function setLatLngAlt (latitude, longitude) {
	center.value.latitude = latitude
	center.value.longitude = longitude
}
// 构造一个marker
function buildOneMarker (latitude, longitude, title, iconPath) {
	return {
		id: new Date().getTime(),
		latitude,
		longitude,
		title,
		iconPath,
		width: 24,
		height: 24,
		anchor: {
			x: 0.5,
			y: 1
		},
		joinCluster: true
	}
}
// 初始化订单数据
function initOrder (id) {
	return new Promise((resolve, reject) => {
		getOrderById(id).then(res => {
			// console.log(res.data)
			order.value = res.data
			resolve(true)
		}).catch(err => {
			reject(err)
		})
	})
	
}
// 初始化markers
function initMarkers () {
	markers.value.push(buildOneMarker(center.value.latitude, center.value.longitude, '您的位置', '/static/location-blue.png'))
	markers.value.push(buildOneMarker(order.value.currentLa, order.value.currentLo, order.value.currentAddr, '/static/location-green.png'))
	markers.value.push(buildOneMarker(order.value.targetLa, order.value.targetLo, order.value.targetAddr, '/static/location-red.png'))
}
// 初始化路线
function initPolyline () {
	MAP.direction({
		mode: 'driving',
		from: `${order.value.currentLa},${order.value.currentLo}`,
		to: `${order.value.targetLa},${order.value.targetLo}`,
		success: (res) => {
			const pll = res.result.routes[0].polyline
			polyline.value[0].points = polylineArray2LatlonArray(pll)
			distance.value = (res.result.routes[0].distance / 1000).toFixed(2)
		},
		fail: (err) => {
			console.error(err)
		}
	})
}
// 获取定位
function getCurrLocation () {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '获取定位中',
			mask: true
		})
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy: true, // 高精度
			success: function (res) {
				const { latitude, longitude } = res
				// 给经纬度赋值
				setLatLngAlt(latitude, longitude)
				// 查询当前位置信息
				MAP.reverseGeocoder({ 
					location: { latitude, longitude },
					success: (addr) => {
						// console.log(addr.result)
						resolve(true)
					},
					fail: (e) => {
						console.error(e)
						reject(e)
					}
				})
			},
			fail: function (err) {
				console.log(err)
				reject(err)
			},
			complete: function (e) {
				uni.hideLoading()
			}
		})
	})
}

// 查看司机信息
function showDriverInfo () {
	driverInfoPopupRef.value.open('center')
}

onLoad(e => {
	// 初始化当前位置
	getCurrLocation().then(() => {
		// 初始化订单信息
		initOrder(e.id).then(() => {
			initMarkers()
			initPolyline()
		})
		// initOrder('202508181635360684').then(() => {
		// 	initMarkers()
		// 	initPolyline()
		// })
	})
	
})
</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	height: 100vh;
	background-color: #fff;
	// 顶部 200
	.head {
		width: 100%;
		height: 200rpx;
		padding-top: 80rpx;
		padding-bottom: 20rpx;
		background: linear-gradient(135deg, #2c3e50, #1a2a3a);
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		position: relative;
		.back {
			position: absolute;
			top: 80;
			left: 0;
			padding: 0 24rpx;
			height: 120rpx;
			display: flex;
			// background-color: red;
			align-items: center;
		}
		.status-bar {
			width: 100%;
			height: 100%;
			color: white;
			text-align: center;
			.status-title {
				font-size: 18px;
				font-weight: bold;
				margin-bottom: 5px;
			}
			.status-desc {
				font-size: 14px;
				opacity: 0.9;
			}
		}
	}
	// 地图 55%
	.map-container {
		width: 100%;
		height: 65%;
		position: relative;
	}
	// 订单卡片
	.order-card {
		position: absolute;
		bottom: 100rpx;
		width: 100%;
		height: calc(100vh - 200rpx - 65% + 100rpx);
		
		background: #f8f8f8;
		border-radius: 30rpx 30rpx 0 0;
		padding: 20rpx 30rpx;
		box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.08);
		
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		
		.up {
			.tags {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 0;
				.left {
					display: flex;
					align-items: center;
					color: #555;
					font-size: 26rpx;
					&>view {
						margin-right: 20rpx;
					}
					.price {
						font-size: 26rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						.num {
							text-align: center;
							font-size: 34rpx;
							font-weight: 600;
							color: #e00;
						}
					}
				}
				.right {
					flex: 1;
					display: flex;
					justify-content: flex-end;
					color: #19afff;
					font-size: 26rpx;
				}
			}
			
			.from-and-to {
				&>view {
					margin-bottom: 20rpx;
					font-size: 28rpx;
					display: flex;
					align-items: center;
					justify-content: flex-start;
					.dot {
						width: 18rpx;
						height: 18rpx;
						border-radius: 50%;
						margin-right: 15rpx;
					}
					.green {
						background-color: #00b400;
					}
					.red {
						background-color: #d60000;
					}
					.text {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 600rpx;
					}
				}
				.from {
				}
				.to {
				}
			}
				
			.time {
				&>view {
					margin-bottom: 20rpx;
					font-size: 28rpx;
					// color: #555;
				}
			}
			
		}
		
		// 按钮样式等
		.down {
			display: flex;
			gap: 15px;
			margin-top: 10px;
			
			.btn {
				flex: 1;
				padding: 25rpx 0;
				font-size: 32rpx;
				font-weight: bold;
				text-align: center;
				border-radius: 20rpx;
				transition: all 0.3s;
			}
			
			.btn-cancel {
				background: linear-gradient(135deg, #ddd, #eee);
				color: #333;
				&:active {
					background: linear-gradient(135deg, #d8d8d8, #e8e8e8);
				}
			}
			
			.btn-contact {
				background: linear-gradient(135deg, #2196F3, #21CBF3);
				color: #fff;
				&:active {
					background: linear-gradient(135deg, #1b8bf3, #1bc5f3);
				}
			}
			
		}
		
	}

	// 司机信息弹窗
	.driver-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-radius: 30rpx;
		background-color: #fff;
		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			margin-right: 30rpx;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 1rpx solid #ccc;
			image {
				width: 100%;
				height: 100%;
			}
		}
		.info {
			flex: 1;
			.name-and-id {
				font-size: 28rpx;
			}
			.years-and-times {
				font-size: 24rpx;
				margin-top: 15rpx;
				color: #888;
			}
		}
	}
}

</style>